﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OracleClient;

namespace BLL.ResourceManage
{
    public class ResMaintain
    {
        string itemValues;
        string itemChanges;
        string itemValueType;
        string itemIsNull;
        string itemValueRemark;
        string strSplitChar = "^";

        string columnsCNName = "";       //所有列以“,”分割
        string columnsENName = "";        //所有列以“,”分割

        string strViewName = "";              //资源视图名称
        string strTableName = "";             //资源表名称
        string strCTableName = "";          //资源中文名称
        string strDateType = "";            //字段数据类型

        string columns;                  // 所有以表名.列以“,”分割

        string strKeyName;             // 存储联合主键的名字，取最后一个主键列的值
        string keyName;
        string keyValue;                //存储联合主键的名字，取最后一个主键列的值
        string sqlCondition = "";
        string strKey;                  // 存储联合主键，各主键名值对以“$”为分隔符，名值以“=”为分隔符
        string strUnionKeys = "";       //存储联合主键

        string isOrderBy = "";              //是否排序
        private readonly OracleDAL.ResourceManage.ResourceBase dal = new OracleDAL.ResourceManage.ResourceBase();
        private readonly OracleDAL.ResourceManage.ResMaintain rm = new OracleDAL.ResourceManage.ResMaintain();

        public void getResQTName(string resid)
        {
            Model.ResourceManage.ResourceBase M = dal.GetModel(resid);
            strViewName = M.QUERYFROMVIEW;
            strTableName = M.MODIFYINFOTABLE;
            strCTableName = M.VIEWINFO;

            isOrderBy = M.ISORDER;
        }
        #region
        public string spliteKey(string resKey)
        {
            string[] resKeyArr;

            resKeyArr = resKey.Split('$');

            for (int splitItem = 0; splitItem < resKeyArr.Length; splitItem++)
            {
                if (resKeyArr[splitItem].IndexOf('=') < 0)
                {
                    return "0";//Alert(Page, "资源表" & strTableName & "在cfg_resource_fields中没有配置主键!请检查。")
                }
                else
                {
                    keyName = strTableName + "." + resKeyArr[splitItem].Substring(0, resKeyArr[splitItem].IndexOf("="));
                    keyValue = resKeyArr[splitItem].Substring(resKeyArr[splitItem].IndexOf("=") + 1);
                    sqlCondition = sqlCondition + keyName + "='" + keyValue + "' and ";
                }
            }
            if (sqlCondition.Length >= 5)
            {
                sqlCondition = sqlCondition.Substring(0, sqlCondition.Length - 5);
            }
            return sqlCondition;
        }
        #endregion

        //修改的查询语句组合，
        public string buildEditSqlString(string resid, string showcolumn, string sqlCondition, string strSort, string strSortDirection)
        {
            string strSqlWhere;
            string sqlSelect = "";
            string sqlFrom = "";
            string sqlWhere = "";
            string strSql = "";
            string[] strCols;

            DataSet ds = new DataSet();
            getResQTName(resid);
            string strReSelect = isOrderBy;
            //if (isTable())
            //{
            strSqlWhere = "iskey='Y' and tablename='" + strTableName + "' order by serial";

            ds = new OracleDAL.ResourceManage.ResAdd().GetList(strSqlWhere);

            for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
            {
                strKey = strKey + "'" + ds.Tables[0].Rows[i]["enfield"].ToString().Trim() + "='||" + strTableName + "." + ds.Tables[0].Rows[i]["enfield"].ToString().Trim() + "||'$'||";
                strKeyName = ds.Tables[0].Rows[i]["enfield"].ToString().Trim();
                // strKey = strKey & "'" & objDataReader("enfield").ToString.Trim & "='||" & strTableName & "." & objDataReader("enfield").ToString.Trim & "||'$'||"
            }
            //组装联合主键
            if (strKey != "" && strKey != null)
            {
                strKey = strKey.Substring(0, strKey.Length - 7);
                strUnionKeys = strKey;
                strKey = strKey + " as id";        //   '& strKeyName
            }
            //理showcolumn为""的情况,显示所有"查询可见"的字段
            if (showcolumn == "")
            {
                strSqlWhere = " ISEDITABLE='Y' and tablename='" + strTableName + "' order by serial";
                ds = new OracleDAL.ResourceManage.ResAdd().GetList(strSqlWhere);
                for (int ishow = 0; ishow <= ds.Tables[0].Rows.Count - 1; ishow++)
                {
                    if (showcolumn == "")
                    {
                        showcolumn = ds.Tables[0].Rows[ishow]["enfield"].ToString().Trim();
                    }
                    else
                    {
                        if (ds.Tables[0].Rows[ishow]["enfield"].ToString().Trim() == "filecontent")
                        {

                        }
                        else
                        {
                            showcolumn = showcolumn + "," + ds.Tables[0].Rows[ishow]["enfield"].ToString().Trim();
                        }
                    }
                }
            }
            // 将联合主键名放到columnsENName中
            if (strKeyName != "")
            {
                columnsENName = strKeyName + "," + showcolumn;
            }
            else
            {
                columnsENName = showcolumn;
            }
            strCols = showcolumn.Split(',');
            sqlFrom = strTableName + ",";        //添加资源基本表名

            for (int item = 0; item < strCols.Length; item++)
            {
                strSqlWhere = "enfield='" + strCols[item] + "' and tablename='" + strTableName + "' and istransition='Y' and valuetype<>'path'";
                ds = new OracleDAL.ResourceManage.ResAdd().GetList(strSqlWhere);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    for (int isql = 0; isql <= ds.Tables[0].Rows.Count - 1; isql++)
                    {
                        //'需要翻译的话，添加联查表名和联查条件
                        sqlSelect = sqlSelect + ds.Tables[0].Rows[isql]["transtable"].ToString().Trim() + item.ToString() + "." + ds.Tables[0].Rows[isql]["transedcol"].ToString().Trim() + ",";
                        sqlFrom = sqlFrom + ds.Tables[0].Rows[isql]["transtable"].ToString().Trim() + " " + ds.Tables[0].Rows[isql]["transtable"].ToString().Trim() + item.ToString() + ",";
                        if (ds.Tables[0].Rows[isql]["remark"].ToString().IndexOf("=") != -1)//有另一个条件
                        {
                            //处理remark中有另外的附加条件的情况，该附加条件是针对翻译表的条件
                            string[] strCon2Arr;
                            string strCon2 = ds.Tables[0].Rows[isql]["remark"].ToString();
                            int num;

                            sqlWhere = sqlWhere + strTableName + "." + strCols[isql] + "=" + ds.Tables[0].Rows[isql]["transtable"].ToString().Trim() + item.ToString() + "." + ds.Tables[0].Rows[isql]["transcol"].ToString().Trim() + "(+) and ";
                            strCon2Arr = strCon2.Split(';');     // remark中的条件要以分号为分隔符

                            for (num = 0; num < strCon2Arr.Length; num++)
                            {
                                sqlWhere = sqlWhere + ds.Tables[0].Rows[isql]["transtable"].ToString().Trim() + item.ToString() + "." + strCon2Arr[num] + " and ";
                            }
                        }
                        else
                        {

                            sqlWhere = sqlWhere + strTableName + "." + strCols[item] + "=" + ds.Tables[0].Rows[isql]["transtable"].ToString().Trim() + item.ToString() + "." + ds.Tables[0].Rows[isql]["transcol"].ToString().Trim() + "(+) and ";
                        }
                    }
                }
                else
                {
                    sqlSelect = sqlSelect + strTableName + "." + strCols[item] + ",";
                    sqlFrom = sqlFrom;
                    sqlWhere = sqlWhere;
                }
            }
            //处理sqlfrom中出复出现的表名
            String[] strArrFrom;
            sqlFrom = sqlFrom.Substring(0, sqlFrom.Length - 1);
            strArrFrom = sqlFrom.Split(',');
            int j;
            string[] tmpArr = sqlFrom.Split(',');
            //int icount=0;
            //for(j=0;j<strArrFrom.Length;j++)
            //{
            //    int k ;
            //    int count = 0;
            //    for (k=0;k<tmpArr.Length;k++)
            //    {
            //        if(tmpArr[k] != strArrFrom[j])
            //        {
            //            count = count + 1;
            //        }
            //    }
            //    if (count == tmpArr.Length+1)
            //    {
            //        tmpArr[icount]=strArrFrom[j];
            //        icount=icount + 1;
            //    }
            //}
            //sqlFrom="";
            //for (j=0; j<tmpArr.Length-1;j++)
            //{
            //    sqlFrom=sqlFrom + tmpArr[j] + ",";
            //}
            //添加条件
            if (sqlCondition == "")
            {
                sqlWhere = sqlWhere + sqlCondition;
            }
            else
            {
                sqlWhere = sqlWhere + sqlCondition + " and ";
            }
            if (sqlSelect != "")
            {
                sqlSelect = sqlSelect.Substring(0, sqlSelect.Length - 1);
            }
            //if(sqlFrom !="")
            //{
            //    sqlFrom = sqlFrom.Substring(0, sqlFrom.Length - 1);
            //}
            sqlWhere = sqlWhere + "1=1";
            if (strKey != "")
            {
                columns = strTableName + "." + "id" + "," + sqlSelect;
            }
            else
            {
                columns = sqlSelect;
            }
            //  }
            //else{
            //      //视图的话——视图暂时没有处理
            //    columnsENName = showcolumn;
            //    columns = showcolumn;
            //    sqlSelect = showcolumn;
            //    sqlFrom = strViewName;
            //    sqlWhere = sqlCondition;
            //}

            if (strKey != "")
            {
                if (strSort != "" || strSortDirection != "")
                {
                    strSql = "select distinct " + strKey + "," + sqlSelect + " from " + sqlFrom + " where " + sqlWhere + " order by " + strSort + " " + strSortDirection;
                }
                else
                {
                    strSql = "select distinct " + strKey + "," + sqlSelect + " from " + sqlFrom + " where " + sqlWhere;
                }
            }
            else
            {
                if (strSort != "" || strSortDirection != "")
                {
                    strSql = "select distinct " + sqlSelect + " from " + sqlFrom + " where " + sqlWhere + " order by " + strSort + " " + strSortDirection;
                }
                else
                {
                    strSql = "select distinct " + sqlSelect + " from " + sqlFrom + " where " + sqlWhere;
                }
            }
            ds.Clear();
            return strSql;
        }
        ///************************************************
        ///*函数名称: getColCNName
        ///*功能描述: 获取中文显示字段名
        ///*参数列表:
        ///*作者    : 
        ///*创建日期: 2009-03-03
        ///************************************************
        public string getColCNName()
        {
            string[] colsArr;
            string strSqlWhere;
            DataSet ds = new DataSet();
            colsArr = columnsENName.Split(',');
            for (int i = 0; i < colsArr.Length; i++)
            {
                strSqlWhere = "upper(enfield) =upper('" + colsArr[i].ToString().Trim() + "') and tablename='" + strTableName + "'";
                ds = new OracleDAL.ResourceManage.ResAdd().GetList(strSqlWhere);
                for (int j = 0; j <= ds.Tables[0].Rows.Count - 1; j++)
                {
                    if (columnsCNName == "")
                    {
                        columnsCNName = ds.Tables[0].Rows[j]["CHFIELD"].ToString().Trim();
                        strDateType = ds.Tables[0].Rows[j]["DATATYPE"].ToString().Trim();
                    }
                    else
                    {
                        columnsCNName = columnsCNName + "," + ds.Tables[0].Rows[j]["CHFIELD"].ToString().Trim();
                        strDateType = strDateType + "," + ds.Tables[0].Rows[j]["DATATYPE"].ToString().Trim();
                    }
                }
            }
            ds.Clear();
            return columnsCNName;
        }
        //
        public void getEditFild(string strsql, string cname, string ename)
        {
            string strSql2;

            DataSet ds = new DataSet();
            DataSet dsTran = new DataSet();
            DataSet dsc = new DataSet();

            string[] itemNameCN = cname.Split(',');
            string[] itemNameEN = ename.Split(',');

            ds = new OracleDAL.ResourceManage.ResMaintain().GetQuery(strsql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                for (int j = 0; j <= ds.Tables[0].Rows.Count - 1; j++)
                {
                    for (int i = 0; i < itemNameEN.Length; i++)
                    {
                        itemValues = itemValues + ds.Tables[0].Rows[0][i].ToString().Trim() + strSplitChar;
                        if (i > 0)
                        {
                            strSql2 = "select enfield from cfg_resource_fields where transedcol='" + itemNameEN[i] + "' and tablename='" + strTableName + "' and chfield='" + itemNameCN[i] + "'";
                            dsTran = new OracleDAL.ResourceManage.ResMaintain().GetQuery(strSql2);
                            if (dsTran.Tables[0].Rows.Count > 0)
                            {
                                for (int tranItem = 0; tranItem <= dsTran.Tables[0].Rows.Count - 1; tranItem++)
                                {
                                    itemChanges = itemChanges + dsTran.Tables[0].Rows[tranItem]["enfield"].ToString().Trim() + ",";
                                    strSql2 = "select valuetype,isnull,remark from cfg_resource_fields where enfield='" + dsTran.Tables[0].Rows[tranItem]["enfield"].ToString().Trim() + "' and tablename='" + strTableName + "' and chfield='" + itemNameCN[i] + "'";
                                    dsc = new OracleDAL.ResourceManage.ResMaintain().GetQuery(strSql2);
                                    for (int scItem = 0; scItem <= dsc.Tables[0].Rows.Count - 1; scItem++)
                                    {
                                        string[] valueTypeArr;
                                        valueTypeArr = dsc.Tables[0].Rows[scItem]["valuetype"].ToString().Trim().Split(',');
                                        if (valueTypeArr.Length > 1)
                                        {
                                            itemValueType = itemValueType + valueTypeArr[0] + ",";
                                        }
                                        else
                                        {
                                            itemValueType = itemValueType + dsc.Tables[0].Rows[scItem]["valuetype"].ToString().Trim() + ",";
                                        }

                                        itemIsNull = itemIsNull + dsc.Tables[0].Rows[scItem]["isnull"].ToString().Trim() + ",";
                                        itemValueRemark = itemValueRemark + dsc.Tables[0].Rows[scItem]["remark"].ToString().Trim() + ",";
                                    }
                                }
                            }
                            else
                            {
                                itemChanges = itemChanges + itemNameEN[i] + ",";
                                strSql2 = "select valuetype,isnull,remark from cfg_resource_fields where enfield='" + itemNameEN[i] + "' and tablename='" + strTableName + "' and chfield='" + itemNameCN[i] + "'";
                                dsc = new OracleDAL.ResourceManage.ResMaintain().GetQuery(strSql2);
                                for (int scItem = 0; scItem <= dsc.Tables[0].Rows.Count - 1; scItem++)
                                {
                                    itemValueType = itemValueType + dsc.Tables[0].Rows[scItem]["valuetype"].ToString().Trim() + ",";
                                    itemIsNull = itemIsNull + dsc.Tables[0].Rows[scItem]["isnull"].ToString().Trim() + ",";
                                    itemValueRemark = itemValueRemark + dsc.Tables[0].Rows[scItem]["remark"].ToString().Trim() + ",";
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                return;
            }
            ds.Clear();
            dsTran.Clear();
            dsc.Clear();

            if (itemValues != "")
            {
                itemValues = itemValues.Substring(0, itemValues.Length - 1);
            }
            if (itemChanges != "")
            {
                itemChanges = itemChanges.Substring(0, itemChanges.Length - 1);
            }
            if (itemValueType != "")
            {
                itemValueType = itemValueType.Substring(0, itemValueType.Length - 1);
            }
            if (itemIsNull != "")
            {
                itemIsNull = itemIsNull.Substring(0, itemIsNull.Length - 1);
            }
            if (itemValueRemark != "")
            {
                itemValueRemark = itemValueRemark.Substring(0, itemValueRemark.Length - 1);
            }
        }
        public string getChangeValue(string filed, string tablename, string swhere)
        {
            string changname = "";
            DataSet ds = new DataSet();
            string strSql = "select " + filed + " from " + tablename + " where " + swhere;
            ds = new OracleDAL.ResourceManage.ResMaintain().GetQuery(strSql);
            for (int Item = 0; Item <= ds.Tables[0].Rows.Count - 1; Item++)
            {
                changname = ds.Tables[0].Rows[Item][filed].ToString().Trim();
            }
            ds.Clear();
            return changname;
        }
        public string getResCNName(string resType)
        {
            DataSet ds = new DataSet();
            string resname = "";
            string strSql = "select viewinfo from cfg_resource_info where resid='" + resType + "'";
            ds = new OracleDAL.ResourceManage.ResMaintain().GetQuery(strSql);
            for (int Item = 0; Item <= ds.Tables[0].Rows.Count - 1; Item++)
            {
                resname = ds.Tables[0].Rows[Item]["viewinfo"].ToString().Trim();
            }
            ds.Clear();
            return resname;
        }
        public string buildEditSql(int number, string items, string condition, string tableName)
        {
            string strSql;
            string updateItem = "";
            string strReturn;

            if (items != "")
            {
                updateItem = items.Substring(0, items.Length - 1);
            }
            strSql = "update " + tableName + " set " + updateItem + " where " + condition;
            Model.ResourceManage.ResMaintain resMain = rm.GetExcutState(strSql);

            if (resMain.GetResult == 0)
            {
                strReturn = "失败";
            }
            else
            {
                strReturn = "成功";
            }
            return strReturn;
        }
        public string getStrDateType()
        {
            return strDateType;
        }

        public string getFuJianName(string FuJianId)
        {
            // string strSql = "select name from accessoriesinfo where id='" + FuJianId + "'";

            return rm.getFuJianName(FuJianId);
        }

        ///*************************************************************************
        ///	函数名称:	getEditColENName
        ///	功能描述:	获取修改列时英文字段串
        ///  参数列表:   
        ///	作    者:	
        ///   创建日期:	2009/03/03  16:17:30
        ///
        ///*************************************************************************
        public string getEditColENName()
        {
            string[] cols;
            cols = columns.Split(',');
            columns = "";
            for (int i = 0; i < cols.Length; i++)
            {
                int j = cols[i].IndexOf(".");
                columns = columns + cols[i].Substring(j + 1) + ",";
            }
            columns = columns.Substring(0, columns.Length - 1);
            return columns;
        }
        public string getItemValues()
        {
            return itemValues;
        }
        public string getItemChanges()
        {
            return itemChanges;
        }
        public string getItemValueType()
        {
            return itemValueType;
        }
        public string getItemIsNull()
        {
            return itemIsNull;
        }
        public string getItemValueRemark()
        {
            return itemValueRemark;
        }
        //返回资源表的中文名称
        public string getCTableName()
        {
            return strCTableName;
        }
        //返回所要操作的视图名称
        public string getViewName()
        {
            return strViewName;
        }
        //返回所要操作的表名称
        public string getTableName()
        {
            return strTableName;
        }
        /// ************************************************
        /// *函数名称: isTable
        /// *功能描述: 判断表cfg_resource_info中查询用字段queryfromview值是表还是视图
        /// *参数列表:
        /// *作者    : 
        /// *创建日期: 2009/02/25
        ///  ************************************************   '
        public bool isTable()
        {
            if (strTableName == strViewName)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        #region 资源查询
        /*
         * 功能说明:资源查询,主要针对表格CFG_RESOURCE_FIELDS、CFG_RESOURCE_INFO的各字段进行查询
         * 编写原因:对上面的代码理解困难,缺乏注释,代码冗余,担心对原系统代码造成影响,故重写部分需要功能的代码
         * 编 写 人:qfkong
         * 编写时间:2010.11.8
         */

        OracleDAL.ResourceManage.ResMaintain rsm = new OracleDAL.ResourceManage.ResMaintain();

        /// <summary>
        /// 获取资源表格字段及其信息
        /// </summary>
        /// <param name="TABLENAME">表名称</param>
        /// <returns></returns>
        public DataSet GetResFields(string TABLENAME)
        {
            return rsm.GetList(" TABLENAME='" + TABLENAME + "'");
        }
        /// <summary>
        /// 获取资源的详细信息
        /// </summary>
        /// <param name="TABLENAME">表名</param>
        /// <param name="ID">资源ID</param>
        /// <returns></returns>
        public DataSet GetResourceInfo(string TABLENAME, string ID)
        {
            return new Common.ResourceStatus().GetResourceValue(TABLENAME, "", "", "", ID);
        }
        #endregion
    }
}
